<?php

namespace app\middleware;

use ReflectionClass;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use Tinywan\Jwt\JwtToken;
use plugin\saiadmin\exception\ApiException;
use support\Cache;
use support\Log;

/**
 * App登录检查中间件
 */
class AppLoginCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {

        // 默认是纹身笔项目
        if(!$request->header('app_project')){
            $request->setHeader('app_project', config('app.defualt_project'));
        }

        // 通过反射获取控制器哪些方法不需要登录
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];

        // 访问的方法需要登录
        if (!in_array($request->action, $noNeedLogin)) {
            try {
                $token_info = JwtToken::getExtend();
                $request->setHeader('check_login', true);
                $request->setHeader('check_admin', $token_info);
            } catch (\Throwable $e) {
                throw new ApiException('您的登录凭证错误或者已过期，请重新登录', 401);
            }

            $userId = $token_info['id'];
            // Log::info('获取token，用户ID：' . $userId . '，token：', [ 'token' => request()->header('authorization') ]);
            if(Cache::get( strval($userId) )!=request()->header('authorization')){
                throw new ApiException('您的登录凭证已过期，请重新登录!', 401);
            }
        }
        return $handler($request);
    }
}
